<template>
  <view class="tn-swipe-action">
    <slot></slot>
  </view>
</template>

<script lang="ts" setup>
import { 
  swipeActionProps, 
  swipeActionEmits, 
  SwipeActionEvent, 
  SwipeActionContext, 
  SwipeActionItemContect, 
  swipeActionContextKey, 
  SwipeEventType 
} from '../../../types/tn-swipe-action'
import { ref, provide } from 'vue'

const props = defineProps(swipeActionProps)
const emits = defineEmits(swipeActionEmits)

let fields: SwipeActionItemContect[] = []

// 添加子元素(组件)
const addField: SwipeActionContext['addField'] = (field: SwipeActionItemContect) => {
  // 如果不存在才添加
  if (!fields.includes(field)) {
    fields.push(field)
  }
}
// 移除子元素(组件)
const removeField: SwipeActionContext['removeField'] = (field: SwipeActionItemContect) => {
  const index = fields.indexOf(field)
  if (index !== -1) {
    fields.splice(index, 1)
  }
}

let activeName = ref<string[]>([])
const handleItemSwipe: SwipeActionContext['handleItemSwipe'] = (type: SwipeEventType, id: string) => {
  const index = activeName.value.indexOf(id)
  if (type === 'close') {
    if (props.autoClose && index === -1) {
      activeName.value = []
    }
    return
  }
  // 如果是自动关闭其他, 只能同时打开一个
  if (props?.autoClose) {
    // 判断是否已经存在，如果已经存在则说明是关闭
    if (index !== -1) {
      activeName.value = []
    } else {
      activeName.value.push(id)
    }
  } else {
    const _activeName: string[] = activeName.value
    if (index !== -1) {
      _activeName.splice(index, 1)
    } else {
      _activeName.push(id)
    }
    activeName.value = _activeName
  }
}

// item点击事件
const handleItemClick: SwipeActionContext['handleItemClick'] = (type: SwipeActionEvent['type'], id: string, btnIndex?: number) => {
  // 查询所在index
  const index = fields.findIndex((field: SwipeActionItemContect) => {
    return field.id === id
  })
  if (index !== -1) {
    emits('click', {
      type,
      name: fields[index].name || index,
      index: typeof btnIndex !== 'undefined' ? btnIndex : index
    })
  }
}

provide(swipeActionContextKey, {
  activeName,
  addField,
  removeField,
  handleItemSwipe,
  handleItemClick
})
</script>

<script lang="ts">
export default {
  options: {
    // 在微信小程序中将组件节点渲染为虚拟节点，更加接近Vue组件的表现(不会出现shadow节点下再去创建元素)
    virtualHost: true
  }
}
</script>

<style lang="scss" scoped>
.tn-swipe-action {
  position: relative;
}
</style>
